import React, { useImperativeHandle, useRef } from "react";
import { createStyles } from "antd-style";
import Filter from './Filter';
import Operator from './Operator';
import { DataAction, IOuterHeaderProps, OnError, ITheme } from "../typing";

interface HeaderProps extends IOuterHeaderProps {
  filter: any;
  height: number;
  dataAction: DataAction;
  onError: OnError;
  doFetchList: () => void;
  setFilter: (filter: any) => void;
  selectedRowKeys: string | number[];
  selectedRows: any[];
  clearSelected: () => void;
  theme: ITheme;
}

const Header = React.forwardRef<{ getHeaderData: () => Promise<{ filter: any }> }, HeaderProps>(({ height, theme, dataAction, onError, doFetchList, setFilter, selectedRowKeys, selectedRows, clearSelected, filterProps, operatorProps }, ref) => {
  const { styles } = useStyle({ height, theme });
  const filterRef = useRef<{ getFilterData: () => Promise<any> }>();

  useImperativeHandle(ref, () => ({
    getHeaderData: () => new Promise<{ filter: any }>((resolve, reject) => {
      setTimeout(() => {
        filterRef.current.getFilterData().then((resp) => {
          resolve({ filter: resp })
        }).catch((e) => reject(e))
      })
    })
  }))

  return <div className={styles.header}>
    <Operator
      dataAction={dataAction}
      onError={onError}
      doFetchList={doFetchList}
      // @ts-ignore
      selectedRowKeys={selectedRowKeys}
      selectedRows={selectedRows}
      clearSelected={clearSelected}
      {...operatorProps}
    />

    <Filter
      ref={filterRef}
      theme={theme}
      setFilter={setFilter}
      {...filterProps}
    />
  </div>
})


export default Header;

const useStyle = createStyles(({ css }, { height, theme }: { height: number, theme: ITheme }) => ({
  header: css`
    width: 100%;
    height: ${height}px;
    display: flex;
    align-items: center;
    padding: 0px 5px;
    background-color: ${theme.headerBgColor};
    box-shadow:${theme.headerBoxShadow};
    overflow: hidden;
  `
}))
